package com.hae.shop.micoshopwechatservice.mp.handler;

import com.hae.shop.common.base.Response;
import com.hae.shop.common.constant.Constants;
import com.hae.shop.common.util.RedisUtil;
import com.hae.shop.common.util.RegexUtils;
import com.hae.shop.micoshopwechatservice.feign.MemberFeign;
import com.hae.shop.micoshopwechatservice.mp.builder.TextBuilder;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
@Slf4j
public class MsgHandler extends AbstractHandler {

	/**
	 * 发送验证码消息
	 */
	@Value("${hae.weixin.registration.code.message}")
	private String registrationCodeMessage;
	/**
	 * 默认回复消息
	 */
	@Value("${hae.weixin.default.registration.code.message}")
	private String defaultRegistrationCodeMessage;

	@Autowired
	private MemberFeign memberFeign;

	@Autowired
	private RedisUtil redisUtil;

	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService weixinService,
			WxSessionManager sessionManager) {

		if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
			// TODO 可以选择将消息保存到本地
		}

		// 当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
		try {
			if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
					&& weixinService.getKefuService().kfOnlineList().getKfOnlineList().size() > 0) {
				return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE().fromUser(wxMessage.getToUser())
						.toUser(wxMessage.getFromUser()).build();
			}
		} catch (WxErrorException e) {
			e.printStackTrace();
		}

		// TODO 组装回复消息
		// 默认消息
		String retContext = defaultRegistrationCodeMessage;
		// 1.验证关键字是否为手机号码类型
		String fromMsg = wxMessage.getContent();
		if (RegexUtils.checkMobile(fromMsg)) {
			// 通过会员服务验证该手机号是否已注册（可以考虑对feign使用aop以应对远程调用失败）
			Response<Boolean> isRegistry = memberFeign.existMobile(fromMsg);
			if (Boolean.TRUE == isRegistry.getResult()) {
				retContext = "手机号已注册，请换一个";
			} else {
				// 判断redis是否存在该手机号，若存在则返回发送频繁，稍后再试
				if (!StringUtils.isEmpty(redisUtil.getString(Constants.WEIXINCODE_KEY + fromMsg))) {
					retContext = "验证码已发送，请稍后再试";
				} else {
					// edis不存在该手机号，则发送短信验证码，可以考虑对真假手机号的验证
					int registCode = registCode();
					// 替换模板中的占位符，即registrationCodeMessage.replaceAll("registrationCodeMessage", registCode + "")
					String content = String.format(registrationCodeMessage, registCode);
					// 将手机号、验证码存入redis
					redisUtil.setString(Constants.WEIXINCODE_KEY + fromMsg, registCode + "", Constants.WEIXINCODE_TIMEOUT);
					retContext = content;
				}
			}
		}

		//返回
		return new TextBuilder().build(retContext, wxMessage, weixinService);

	}

	// 获取注册码
	private int registCode() {
		int registCode = (int) (Math.random() * 9000 + 1000);
		return registCode;
	}


}
